package intercept

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"wrblog-api-go/app/common/token"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/result"
)

func IsPermission(per ...string) gin.HandlerFunc {
	return func(c *gin.Context) {
		path := c.Request.RequestURI
		row, exists := c.Get("loginUser")
		if !exists {
			result.Fail(errs.New(http.StatusUnauthorized, fmt.Sprintf("请求访问：%s,认证失败！", path))).Json(c)
			c.Abort() //停止执行
		}
		loginUser := row.(token.LoginUser)
		isOk := containsArr(per, loginUser.Permissions)
		if !isOk {
			result.Fail(errs.New(http.StatusForbidden, fmt.Sprintf("抱歉，你没有此接口权限：%s", path))).Json(c)
			c.Abort()
			return
		}
		c.Next()
	}
}

func containsArr(slice []string, targets []string) bool {
	for _, item := range slice {
		for _, itemT := range targets {
			if item == itemT || itemT == "*:*:*" {
				return true
			}
		}
	}
	return false
}

func contains(slice []string, target string) bool {
	for _, item := range slice {
		if item == target {
			return true
		}
	}
	return false
}
